<template>
    <!-- 弹框：分为新增与编辑模式 -->
    <div class="dialog">
        <div class="mask"></div>
        <div class="box">
            <div class="top flex_btw">
                <span>{{type=='new'?'添加日志':'编辑日志'}}</span>
                <i class="iconfont icon-guanbi" @click="$emit('close')" style="cursor: pointer;"></i>
            </div>
            <div class="content">
                <Input label="标题" :value.sync="formData.title"/>
                <textarea v-model="formData.content" cols="60" rows="10"></textarea>
                <Button :value="type=='new'?'提交':'更新'" @click="submit"/>
            </div>
        </div>
    </div>
</template>
<script>
import { mapGetters } from 'vuex'
import Input from '../../components/FormItem.vue'
import Button from '../../components/Button.vue'
export default{
    props:['type'],
    components:{
        Input,
        Button
    },
    computed: {
        ...mapGetters([
            'getArticle',
        ])
    },
    data(){
        return{
            formData:{
                title:'',
                content:''
            }
        }
    },
    mounted(){
        // 如果是新建，清空数据
        if(this.type=='new'){
            this.formData.title=''
            this.formData.content=''
        }else{
        // 如果是编辑 重新赋值
            this.formData.title=this.getArticle.title
            this.formData.content=this.getArticle.content
        }
    },
    methods:{
        submit(){
            // 1 先验证
            let {title,content}=this.formData
            if(title==''){
                alert('标题不能为空')
                return
            }
            if(content==''){
                alert('内容不能为空')
                return
            }

            // 判断是新增还是编辑
            if(this.type=='new'){
                let id=new Date().getTime()
                this.formData.id=id
                this.$store.commit('createArticle',this.formData)
                alert('创建成功')
                this.$emit('close')
            }else{
                console.log('this.formData2',this.formData)
                this.$store.commit('updateArticle',this.formData)
                alert('更新成功')
                this.$emit('close')
            }
        }
    }
}
</script>
<style scoped lang="less">
.dialog{
    position: relative;
    .mask{
        position: fixed;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: #eee;
        z-index: 2;
        opacity: .8;
    }
    .box{
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        background: white;
        padding: 1em;
        z-index: 3;
        border-radius: .4em;
    }
    .content{
        margin-top: 1em;
        text-align: right;
        .button{
            text-align: center;
        }
    }
}
</style>

